<template>
  <div class="study-management">
    <h2 class="title">学习管理</h2>
    <div class="toolbar">
      <el-input
          v-model="searchQuery"
          placeholder="搜索课程名称"
          style="width: 200px; margin-right: 10px;"
          @input="fetchStudies"
      />
      <el-button type="primary" @click="openAddDialog">添加课程</el-button>
    </div>
    <el-table :data="studies" style="width: 100%">
      <el-table-column prop="courseName" label="课程名称"></el-table-column>
      <el-table-column label="总进度">
        <template slot-scope="scope">
          <el-progress :percentage="scope.row.totalProgress" />
        </template>
      </el-table-column>
      <el-table-column prop="createdAt" label="创建时间" :formatter="formatDate"></el-table-column>
      <el-table-column prop="updatedAt" label="修改时间" :formatter="formatDate"></el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button size="mini" @click="editStudy(scope.row.id)">编辑</el-button>
          <el-button size="mini" type="danger" @click="confirmDelete(scope.row.id)">删除</el-button>
          <el-button size="mini" @click="showDetails(scope.row.id)">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
        background
        layout="prev, pager, next"
        :total="total"
        :page-size="pageSize"
        :current-page.sync="page"
        @current-change="fetchStudies"
    ></el-pagination>

    <!-- 添加/编辑课程对话框 -->
    <el-dialog :visible.sync="dialogVisible" title="添加/编辑课程" width="50%" @close="handleDialogClose">
      <el-form :model="newStudy" :rules="rules" ref="studyForm" class="study-form" label-width="120px">
        <el-form-item label="课程名称" prop="courseName">
          <el-input v-model="newStudy.courseName"></el-input>
        </el-form-item>
        <el-form-item label="总进度" prop="totalProgress">
          <el-progress :percentage="newStudy.totalProgress" />
        </el-form-item>
        <el-form-item label="课程描述" prop="courseDescription">
          <el-input v-model="newStudy.courseDescription"></el-input>
        </el-form-item>
        <el-divider>详细信息</el-divider>
        <div v-for="(detail, index) in newStudy.courseDetailsRequests" :key="index" class="detail-item">
          <el-form-item label="章节名称" :prop="'courseDetailsRequests.' + index + '.chapterName'">
            <el-input v-model="detail.chapterName"></el-input>
          </el-form-item>
          <el-form-item label="进度" :prop="'courseDetailsRequests.' + index + '.progress'">
            <el-slider v-model="detail.progress" :min="0" :max="100" @input="updateTotalProgress(index)"></el-slider>
          </el-form-item>
          <el-button type="danger" @click="removeDetail(index)" class="remove-detail-button">删除</el-button>
          <el-divider></el-divider>
        </div>
        <el-button type="primary" @click="addDetail" class="add-detail-button">添加章节</el-button>
        <el-form-item>
          <el-button type="primary" @click="validateForm">{{ isEditing ? '更新' : '添加' }}</el-button>
          <el-button @click="resetForm">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog :visible.sync="detailsDialogVisible" title="课程详情" width="50%">
      <el-form :model="detailsStudy" label-width="120px" class="study-form">
        <el-form-item label="课程名称">
          <el-input :value="detailsStudy.courseName" disabled></el-input>
        </el-form-item>
        <el-form-item label="总进度">
          <el-progress :percentage="detailsStudy.totalProgress" />
        </el-form-item>
        <el-form-item label="课程描述">
          <el-input :value="detailsStudy.courseDescription" disabled></el-input>
        </el-form-item>
        <el-divider>详细信息</el-divider>
        <div v-for="(detail, index) in detailsStudy.courseDetailsRequests" :key="index">
          <el-form-item label="章节名称">
            <el-input :value="detail.chapterName" disabled></el-input>
          </el-form-item>
          <el-form-item label="进度">
            <el-slider v-model="detail.progress" :min="0" :max="100" disabled></el-slider>
          </el-form-item>
          <el-divider></el-divider>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';
import { Message, MessageBox } from 'element-ui';

export default {
  name: 'StudyManagement',
  data() {
    return {
      studies: [],
      searchQuery: '',
      newStudy: {
        id: '',
        courseName: '',
        totalProgress: 0,
        courseDescription: '',
        courseDetailsRequests: [],
        createdAt: '',
        updatedAt: ''
      },
      detailsStudy: {
        id: '',
        courseName: '',
        totalProgress: '',
        courseDescription: '',
        courseDetailsRequests: [],
        createdAt: '',
        updatedAt: ''
      },
      isEditing: false,
      total: 0,
      page: 1,
      pageSize: 10,
      dialogVisible: false,
      detailsDialogVisible: false,
      rules: {
        courseName: [{ required: true, message: '请输入课程名称', trigger: 'blur' }],
        courseDescription: [{ required: true, message: '请输入课程描述', trigger: 'blur' }],
        courseDetailsRequests: {
          type: 'array',
          required: true,
          defaultField: {
            type: 'object',
            fields: {
              chapterName: { required: true, message: '请输入章节名称', trigger: 'blur' },
              progress: { required: true, message: '请输入进度', trigger: 'blur' }
            }
          }
        }
      }
    };
  },
  created() {
    this.fetchStudies();
  },
  methods: {
    fetchStudies() {
      axios.get('/study/list', {
        params: {
          page: this.page,
          pageSize: this.pageSize,
          courseName: this.searchQuery
        }
      })
          .then(response => {
            this.studies = response.data.data.rows;
            this.total = response.data.data.records;
          })
          .catch(error => {
            console.error('Error fetching studies:', error);
          });
    },
    addStudy() {
      axios.post('/study/add', this.newStudy)
          .then(() => {
            this.fetchStudies();
            this.resetForm();
            Message.success('添加成功');
          })
          .catch(error => {
            console.error('Error adding study:', error);
          });
    },
    editStudy(id) {
      axios.get(`/study/get/${id}`)
          .then(response => {
            const study = response.data.data;
            this.newStudy = {
              ...study,
              courseDetailsRequests: Array.isArray(study.courseDetailsRequests) ? [...study.courseDetailsRequests] : []
            };
            this.isEditing = true;
            this.dialogVisible = true;
          })
          .catch(error => {
            console.error('Error fetching study details:', error);
          });
    },
    updateStudy() {
      axios.put('/study/update', this.newStudy)
          .then(() => {
            this.fetchStudies();
            this.resetForm();
            Message.success('更新成功');
          })
          .catch(error => {
            console.error('Error updating study:', error);
          });
    },
    confirmDelete(id) {
      MessageBox.confirm('此操作将永久删除该记录, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteStudy(id);
      }).catch(() => {
        Message.info('已取消删除');
      });
    },
    deleteStudy(id) {
      axios.delete(`/study/delete/${id}`)
          .then(() => {
            this.fetchStudies();
            Message.success('删除成功');
          })
          .catch(error => {
            console.error('Error deleting study:', error);
          });
    },
    resetForm() {
      this.newStudy = {
        id: '',
        courseName: '',
        totalProgress: 0,
        courseDescription: '',
        courseDetailsRequests: [],
        createdAt: '',
        updatedAt: ''
      };
      this.isEditing = false;
      this.dialogVisible = false;
    },
    handleDialogClose() {
      this.resetForm();
    },
    openAddDialog() {
      this.resetForm();
      this.isEditing = false;
      this.dialogVisible = true;
    },
    validateForm() {
      this.$refs.studyForm.validate((valid) => {
        if (valid) {
          this.isEditing ? this.updateStudy() : this.addStudy();
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    addDetail() {
      if (!this.newStudy.courseDetailsRequests) {
        this.$set(this.newStudy, 'courseDetailsRequests', []);
      }
      this.newStudy.courseDetailsRequests.push({
        chapterName: '',
        progress: 0
      });
    },
    removeDetail(index) {
      this.newStudy.courseDetailsRequests.splice(index, 1);
      this.updateTotalProgress();
    },
    updateTotalProgress() {
      this.newStudy.totalProgress = this.newStudy.courseDetailsRequests.reduce((sum, detail) => sum + parseFloat(detail.progress || 0), 0).toFixed(2);
    },
    formatDate(row, column, value) {
      if (!value) return '';
      const date = new Date(value);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}:${String(date.getSeconds()).padStart(2, '0')}`;
    },
    showDetails(id) {
      axios.get(`/study/get/${id}`)
          .then(response => {
            const study = response.data.data;
            this.detailsStudy = {
              ...study,
              courseDetailsRequests: Array.isArray(study.courseDetailsRequests) ? [...study.courseDetailsRequests] : []
            };
            this.detailsDialogVisible = true;
          })
          .catch(error => {
            console.error('Error fetching study details:', error);
          });
    }
  }
};
</script>

<style scoped>
.study-management {
  height: 100vh;
  overflow: hidden;
  background-image: url('../assets/pdx.png'); /* 确保路径正确 */
  background-size: cover;
  background-position: center;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: center;
  padding: 20px;
}

.title {
  color: black;
  margin-top: 20px;
}

.toolbar {
  width: 100%;
  display: flex;
  justify-content: flex-start;
  margin-bottom: 20px;
}

.study-form {
  width: 100%;
  margin-bottom: 20px;
}

.el-form-item {
  margin-bottom: 10px;
}

.detail-item {
  border: 1px solid #ddd;
  padding: 10px;
  margin-bottom: 20px; /* 增加底部的间距 */
  border-radius: 4px;
  background-color: #f9f9f9;
}

.add-detail-button {
  margin-bottom: 20px; /* 添加按钮底部增加间距 */
}
</style>
